#include "BoundingSphereRenderer.h"
#include "MathHelper.h"
#include "MatrixHelper.h"
#include "GraphicsDeviceManager.h"

BoundingSphereRenderer::BoundingSphereRenderer()
{
}

BoundingSphereRenderer::~BoundingSphereRenderer()
{
}

void BoundingSphereRenderer::Initialize()
{
	Vertex vertices[BOUNDINGSPHERERENDERER_VERTEX_COUNT];

	for(int a = 0; a < BOUNDINGSPHERERENDERER_VERTEX_COUNT; a++)
	{
		Vertex vertex;

		float angle = (PI * 2.0f) * (a / (float)BOUNDINGSPHERERENDERER_VERTEX_COUNT);

		vertex.Position.X = cos(angle);
		vertex.Position.Y = sin(angle);

		vertices[a] = vertex;
	}

	m_pVertexBuffer = new VertexBuffer();
	m_pVertexBuffer->SetData(vertices, sizeof(Vertex) * BOUNDINGSPHERERENDERER_VERTEX_COUNT);

	unsigned int indices[BOUNDINGSPHERERENDERER_INDEX_COUNT];

	memset(indices, 0, sizeof(indices));

	for(int a = 0; a < BOUNDINGSPHERERENDERER_VERTEX_COUNT; a++)
	{
		indices[a] = a;
	}

	m_pIndexBuffer = new IndexBuffer();
	m_pIndexBuffer->SetData(indices, sizeof(unsigned int) * BOUNDINGSPHERERENDERER_INDEX_COUNT);

	m_bInitialized = true;
}

void BoundingSphereRenderer::Draw(const BoundingSphere& boundingSphere)
{
	if(!m_bInitialized)
	{
		Initialize();
	}

	glDisable(GL_LIGHTING);
	glPushMatrix();
	glTranslatef(boundingSphere.Position.X, boundingSphere.Position.Y, boundingSphere.Position.Z);
	glScalef(boundingSphere.Radius, boundingSphere.Radius, boundingSphere.Radius);
	glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_pVertexBuffer->GetID());
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m_pIndexBuffer->GetID());
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);

	glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));
	glColorPointer(4, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(sizeof(Vector3f)));

	for(float a = 0.0f; a < PI * 2; a += PI / 4)
	{
		MatrixHelper::MultiplyRotation(Quaternion::CreateFromAxisAngle(Vector3f::Up, a));

		glDrawElements(GL_LINE_STRIP, BOUNDINGSPHERERENDERER_INDEX_COUNT, GL_UNSIGNED_INT, 0);
	}

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
	glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
	glPopMatrix();
}

bool BoundingSphereRenderer::m_bInitialized = false;
IndexBuffer* BoundingSphereRenderer::m_pIndexBuffer;
VertexBuffer* BoundingSphereRenderer::m_pVertexBuffer;